package com.dtsz.m2.ui.dashboard;

import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.android.volley.Request;
import com.dtsz.m2.R;
import com.dtsz.m2.config.UrlConfig;
import com.dtsz.m2.refresh.LoadingFooter;
import com.dtsz.m2.ui.activity.CreateGestureActivity;
import com.dtsz.m2.ui.activity.IdentificationCardActivity;
import com.dtsz.m2.ui.activity.LoginActivity;
import com.dtsz.m2.ui.activity.Pay1Activity;
import com.dtsz.m2.ui.adapter.MyEcologyOrderAdatper;
import com.dtsz.m2.ui.base.BaseFragment;
import com.dtsz.m2.ui.inter.OnPasswordInputFinish;
import com.dtsz.m2.ui.model.EcologyOrder;
import com.dtsz.m2.ui.model.Users;
import com.dtsz.m2.ui.widget.PopEnterResetPassword;
import com.dtsz.m2.utils.RSAEncrypt;
import com.dtsz.m2.utils.StringUtils;
import com.dtsz.m2.volley.state.HUCState;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class DashboardFragment extends BaseFragment implements com.dtsz.m2.refresh.xRecyclerView.OnRefreshListener, OnPasswordInputFinish {

    private TextView tvName, tvNumYes, tvAccountNumber;
    private com.dtsz.m2.refresh.xRecyclerView xRecyclerView;

    private MyEcologyOrderAdatper ecologyOrderAdatper;
    private List<EcologyOrder> ecologyOrderList = new ArrayList<>();
    private boolean refreshFlag = true;
    AlertDialog alertDialog1;

    private String buCertification;//是否实名认证
    private String biIm;//实名允许实名认证

    private Users users;
    private View view;
    private PopEnterResetPassword popEnterPassword;
    private FrameLayout frameLayout;


    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View root = inflater.inflate(R.layout.fragment_dashboard, container, false);
        view = root;
        root.findViewById(R.id.tv_zc).setOnClickListener(this);
        tvName = root.findViewById(R.id.tv_name);
        tvNumYes = root.findViewById(R.id.tv_num_yes);
        tvAccountNumber = root.findViewById(R.id.tv_account_number);
        tvAccountNumber.setOnClickListener(this);
        root.findViewById(R.id.tv_account).setOnClickListener(this);
        xRecyclerView = root.findViewById(R.id.xrecyclerView);
        ecologyOrderAdatper = new MyEcologyOrderAdatper(getActivity(), R.layout.item_pay, ecologyOrderList);
        xRecyclerView.setAdapter(getActivity(), ecologyOrderAdatper, new LinearLayoutManager(getActivity()));
        xRecyclerView.setOnRefreshListener(this);
        //插入banner广告
        return root;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_zc:
                if ("0".equals(biIm) || StringUtils.isEmpty(biIm)) {
                    Toast.makeText(getActivity(), "账号未授权实名认证", Toast.LENGTH_LONG).show();
                } else {
                    if (!"1".equals(buCertification)) {
                        showToast("请先完成实名认证");
                    } else {
//                        List<String> list = new ArrayList<>();
//                        list.add("M2钱包");
//                        list.add("第一生态");
//
//                        new SuperDialog.Builder(getActivity())
//                                //.setAlpha(0.5f)
//                                //.setGravity(Gravity.CENTER)
//                                //.setTitle("上传头像", ColorRes.negativeButton)
//                                .setCanceledOnTouchOutside(false)
//                                .setItems(list, new SuperDialog.OnItemClickListener() {
//                                    @Override
//                                    public void onItemClick(int position) {
//                                        Toast.makeText(getActivity(), list.get(position), Toast.LENGTH_LONG).show();
//                                    }
//                                })
//                                .setNegativeButton("取消", null)
//                                .build();
                        sendIntent(getActivity(), Pay1Activity.class);
                    }
                }
                break;
            case R.id.tv_account_number:
            case R.id.tv_account:
                Clipboard(tvAccountNumber.getText().toString());
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hucRequestInterfase.cancelAll();

    }


    public void Clipboard(String text) {
        try {
            final ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(getActivity().CLIPBOARD_SERVICE);
            ClipData textCd = ClipData.newPlainText("data", text);
            clipboard.setPrimaryClip(textCd);
            Toast.makeText(getActivity(), "复制成功", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initData() {

        hucRequestInterfase.executeStr(this, Users.class,
                HUCState.HUC_REQEUST_CODE_1, Request.Method.POST, UrlConfig.USERS_URL,
                hucParameInterfase.getRequestParameter(pageVo), true);
    }


    @Override
    public void onSuccessfulStrType(int inputType, Object response) {
        super.onSuccessfulStrType(inputType, response);
        switch (inputType) {
            case HUCState.HUC_REQEUST_CODE_1:
                if (response instanceof Users) {
                    Users user = (Users) response;
                    users = user;
                    buCertification = user.getBuCertification();
                    biIm = user.getBuIm();
                    String rekey = user.getBuRsaKey();
                    tvName.setText("姓名：" + user.getBuName());
                    tvNumYes.setText("M2币 ：" + user.getBuSumYes() + "㎡");
                    tvAccountNumber.setText(user.getBuAccountNumber());
                    if (StringUtils.isEmpty(rekey) || rekey.indexOf("-") != -1) {
                        //sendIntent(getActivity(), CreateGestureActivity.class);
                        //设置支付密码
                        if (popEnterPassword == null) {
                            popEnterPassword = new PopEnterResetPassword(this, getActivity());// 显示窗口
                            View viewP = view.findViewById(R.id.tv_zc);
                            popEnterPassword.showAtLocation(viewP,
                                    Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); // 设置layout在PopupWindow中显示的位置
                        }

                    }
                } else {
                    Toast.makeText(getActivity(), response.toString(), Toast.LENGTH_SHORT).show();
                }
                break;
            case HUCState.HUC_REQEUST_CODE_2:
                if (response instanceof List) {
                    List<EcologyOrder> ecologyOrderListResult = (List<EcologyOrder>) response;
                    if (refreshFlag) {
                        if (ecologyOrderListResult == null || ecologyOrderListResult.size() == 0) {
                            if (ecologyOrderList.size() == 0) {
                                xRecyclerView.refreshComplete(LoadingFooter.State.NoData, "");
                            } else {
                                xRecyclerView.refreshComplete(LoadingFooter.State.TheEnd, "");
                            }
                        } else {
                            for (EcologyOrder notice : ecologyOrderListResult) {
                                ecologyOrderList.add(notice);
                            }
                            ecologyOrderAdatper.notifyDataSetChanged();
                            xRecyclerView.refreshComplete(LoadingFooter.State.Normal, "");
                        }
                    } else {
                        ecologyOrderList.clear();
                        for (EcologyOrder notice : ecologyOrderListResult) {
                            ecologyOrderList.add(notice);
                        }
                        ecologyOrderAdatper.notifyDataSetChanged();
                        xRecyclerView.refreshComplete(LoadingFooter.State.Normal, "");
                    }
                }
                break;
            case HUCState.HUC_REQEUST_CODE_3:
                if (response instanceof String) {
                    String msg = (String) response;
                    showToast(msg);
                    if ("设置成功".equals(msg)) {
                        if (popEnterPassword != null) {
                            popEnterPassword.dismiss();
                            popEnterPassword = null;
                        }
                    }
                }
                break;
        }
        loadDismiss();
    }

    /**
     * 下拉刷新
     *
     * @param refreshLayout
     */
    @Override
    public void refresh(SwipeRefreshLayout refreshLayout) {
        onStart();
    }

    @Override
    public void onErrorLogin(int inputType) {
        super.onErrorLogin(inputType);
        setSharedPreferences("tokenRSA", "token001");
        getActivity().finish();
        sendIntent(getActivity(), LoginActivity.class);
    }

    @Override
    public void onStart() {
        super.onStart();
        refreshFlag = false;
        pageVo.setCurrent(1 + "");
        pageVo.setSize(10 + "");
        getInitData();
        initData();
    }

    private void isIdentif() {
        //判断是否绑定姓名
        AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
        // dialog.setTitle("绑定姓名");
        dialog.setMessage("转出需要实名认证审核通过，请点击按钮实名认证");
        dialog.setPositiveButton("实名认证", null);
        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                alertDialog1.dismiss();
            }
        });

        alertDialog1 = dialog.create();
        alertDialog1.setCancelable(false);
        alertDialog1.show();

        //为了避免点击 positive 按钮后直接关闭 dialog,把点击事件拿出来设置
        alertDialog1.getButton(AlertDialog.BUTTON_POSITIVE)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //绑定用户v
                        alertDialog1.dismiss();
                        Intent intent = new Intent();
                        intent.setClass(getActivity(), IdentificationCardActivity.class);
                        intent.putExtra("name", users.getBuName());
                        intent.putExtra("card", users.getBuCard());
                        startActivity(intent);
                    }
                });
    }

    /**
     * 上拉加载
     *
     * @param recyclerView
     */
    @Override
    public void loadMore(RecyclerView recyclerView) {
        refreshFlag = true;
        int CurrentCount = Integer.parseInt(pageVo.getCurrent()) + 1;
        pageVo.setCurrent(CurrentCount + "");
        pageVo.setSize(10 + "");
        getInitData();
    }


    private void getInitData() {
        hucRequestInterfase.executeStr(this, EcologyOrder.class,
                HUCState.HUC_REQEUST_CODE_2, Request.Method.POST, UrlConfig.MY_ECOLOGYS_URL,
                hucParameInterfase.getRequestParameter(pageVo), false);
    }

    @Override
    public void inputFinish(String password) {
        loading();
        pageVo.setRsa(RSAEncrypt.encrypt(password));
        hucRequestInterfase.executeStr(this, Users.class,
                HUCState.HUC_REQEUST_CODE_3, Request.Method.POST, UrlConfig.RSA_URL,
                hucParameInterfase.getRequestParameter(pageVo), true);
    }
}
